#include "settings/command_line.h"

namespace Tvimeg
{
	CommandLine::CommandLine(void)
	{
	}

	CommandLine::~CommandLine(void)
	{
	}

	void CommandLine::Initialise(const int argumentCount, const char* arguments[])
	{
		std::string currentKey;

		for (int index = 1; index < argumentCount; ++index)
		{
			std::string string(arguments[index]);
			if (string.length() > 0)
			{
				if (!currentKey.empty() && string[0] != '-')
				{
					commands[currentKey] = string;
					currentKey.clear();
				}
				else
				{
					if (!currentKey.empty())
					{
						commands[currentKey] = "1";
						currentKey.clear();
					}

					int charsToRemove = 1;
					if (string.length() > 1 && string[1] == '-')
					{
						charsToRemove = 2;
					}

					string = string.substr(charsToRemove);

					if (!string.empty())
					{
						const size_t equalPos = string.find('=');
						if (equalPos == std::string::npos)
						{
							currentKey = string;
						}
						else
						{
							const std::string key = string.substr(0, equalPos);
							const std::string value = string.substr(equalPos + 1);
							commands[key] = value;
							currentKey.clear();
						}
					}
				}
			}
		}

		if (!currentKey.empty())
		{
			commands[currentKey] = "1";
		}
	}

	const std::string& CommandLine::GetCommand(const std::string& key) const
	{
		const CommandList::const_iterator found = commands.find(key);
		if (found != commands.end())
		{
			return found->second;
		}
		else
		{
			static const std::string empty;
			return empty;
		}
	}
}
